package XynLeen.GraduationProject.Activities;

import android.app.AlarmManager;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.classic.adapter.BaseAdapterHelper;
import com.classic.adapter.CommonAdapter;

import org.litepal.crud.DataSupport;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import XynLeen.GraduationProject.Bean.ScheduleBean;
import XynLeen.GraduationProject.R;
import XynLeen.GraduationProject.Utils.Alarm.AlarmMang;
import XynLeen.GraduationProject.Utils.Alarm.AlarmReceiver;
import XynLeen.GraduationProject.view.BaseActivity;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class Activity_Schedule extends BaseActivity implements AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {


    @Bind(R.id.list_view)
    ListView mListView;
    @Bind(R.id.ib_navigation_back)
    ImageButton mIbNavigation_back;
    @Bind(R.id.ib_navigation_add)
    ImageButton mIbNavigation_add;
    @Bind(R.id.tv_navigation_label)
    TextView mTvNavigation;

    public CommonAdapter<ScheduleBean> quickAdapter;

    private String type;

    public SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        type=getIntent().getStringExtra("type");
        initQuickAdapte();
        initData();
        mListView.setOnItemClickListener(this);
        mListView.setOnItemLongClickListener(this);

        mTvNavigation.setText("事务提醒");
    }

    @Override
    public void onResume() {
        super.onResume();
        initData();
    }

    public void initQuickAdapte() {

        quickAdapter = new CommonAdapter<ScheduleBean>(this, R.layout.adapter_listview_schdule, null) {

            @Override
            public void onUpdate(BaseAdapterHelper helper, ScheduleBean bean, int position) {


                TextView fieldname1 = helper.getView(R.id.fieldname1);
                fieldname1.setText(bean.getTitle());
                TextView fieldname2 = helper.getView(R.id.fieldname2);
                fieldname2.setText(bean.getTime());
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");

                TextView fieldname4 = helper.getView(R.id.fieldname4);

                helper.setText(R.id.fieldname4,bean.getType());
                helper.setVisible(R.id.fieldname4,true);
                if("重要".equals(bean.getType())){
                    fieldname4.setTextColor(getResources().getColor(R.color.green));
                }else if("一般重要".equals(bean.getType())){
                    fieldname4.setTextColor(getResources().getColor(R.color.budget_in));
                }else {
                    fieldname4.setTextColor(getResources().getColor(R.color.red));
                }

                ImageView icon_clock = helper.getView(R.id.clock);
                if ("1".equals(bean.getIsAlarm())) {
                    icon_clock.setVisibility(View.VISIBLE);
                } else {
                    icon_clock.setVisibility(View.GONE);
                }

            }
        };
    }

    public void initData() {
        if(TextUtils.isEmpty(type)){
            List<ScheduleBean> list = DataSupport.order("time").find(ScheduleBean.class);
            quickAdapter.clear();
            mListView.setAdapter(quickAdapter);
            quickAdapter.addAll(list);
            quickAdapter.notifyDataSetChanged();
        }else {
            List<ScheduleBean> list = DataSupport.where("leixing=?",type).order("time").find(ScheduleBean.class);
            quickAdapter.clear();
            mListView.setAdapter(quickAdapter);
            quickAdapter.addAll(list);
            quickAdapter.notifyDataSetChanged();
        }

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        final ScheduleBean bean = quickAdapter.getItem(position);
        Intent intent = new Intent(this, Activity_Schedule_Add.class);
        intent.putExtra("bean", bean);
        intent.putExtra("title", "修改");
        startActivity(intent);
    }


    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        final ScheduleBean bean = quickAdapter.getItem(position);

        final AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("日程提醒设定")//设置对话框的标题
                .setMessage("请选择")//设置对话框的内容
                //设置对话框的按钮
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        stopAlarm(bean);
                        dialog.dismiss();
                    }
                })
                .setPositiveButton("设定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        setAlarm(bean);
                        dialog.dismiss();
                    }
                }).create();

        dialog.show();
        return true;
    }

    private void stopAlarm(ScheduleBean bean) {
        AlarmMang.cancelAlarmBroadcast(this, bean.getId(), AlarmReceiver.class);
        bean.setIsAlarm("2");
        bean.setTxtime("");
        bean.update(bean.getId());
        initData();
    }

    private void setAlarm(final ScheduleBean bean) {

        //时间选择器
        TimePickerView pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                bean.setIsAlarm("1");
                bean.setTxtime(formatter.format(date.getTime()));
                bean.update(bean.getId());
                quickAdapter.notifyDataSetChanged();
                AlarmMang.sendAlarmBroadcast(Activity_Schedule.this, bean.getId(), AlarmManager.RTC_WAKEUP, date.getTime(), AlarmReceiver.class, bean.getTitle());
            }
        }).setType(new boolean[]{true, true, true, true, true, true})// 默认全部显示
                .build();
        pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
        pvTime.show();

    }




    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }


    @Override
    public int getLayoutId() {
        return R.layout.activity_schedule;
    }

    @Override
    public void initData(Bundle savedInstanceState) {

    }

    @Override
    public void initView() {

    }

    @OnClick({R.id.ib_navigation_back,R.id.ib_navigation_add})
    public void OnClick(View v){
        switch (v.getId()){
            case R.id.ib_navigation_back:
                finish();
                break;
            case R.id.ib_navigation_add:
                Intent intent = new Intent(this, Activity_Schedule_Add.class);
                startActivity(intent);
                break;
        }
    }


}
